package itsm.isperp.module.controller.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.module.entity.announcement.AnnoAnnouncement;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppPortal;
import itsm.isperp.module.entity.knowledge.KngKnowledgeItem;
import itsm.isperp.module.service.announcement.AnnouncementService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppPortalService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.knowledge.KngKnowledgeItemService;
import itsm.isperp.report.Counter;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.series.Series;

/**
 * 
 * @author lizx
 * @date 2014-3-24
 */
@Controller
@RequestMapping("app/portal/main")
public class AppMainPortalController extends BaseController<AppPortal> {

  @Autowired
  protected AppPortalService appPortalService;

  @Autowired
  protected AppUserService appUserService;

  @Autowired
  protected KngKnowledgeItemService kngKnowledgeItemService;

  @Override
  public AppPortalService getService() {
    return this.appPortalService;
  }

  @Override
  public String getPageTitle() {
    return "系统门户";
  }

  @RequestMapping("userInfoEdit")
  public ModelAndView userInfoEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    IUser u = ContextHolder.getLoginUser();
    String userId = u.getId();
    Map<String, Object> user = appUserService.findOneDetailById(userId);
    if (user.get("photo") == null) {
      user.put("photo", "");
    }
    mv.addObject("model", user);
    return mv;
  }

  @RequestMapping("getTop5Knowledge")
  @ResponseBody
  public List<KngKnowledgeItem> getTop5Knowledge(HttpServletRequest req)
      throws Exception {
    List<KngKnowledgeItem> klg = kngKnowledgeItemService.getNewTop10Item(5, "");
    return klg;
  }

  @RequestMapping("convenientEnterEdit")
  public ModelAndView convenientEnterEdit(HttpServletRequest req)
      throws Exception {
    ModelAndView mv = this.getModelAndView();
    IUser u = ContextHolder.getLoginUser();
    String userId = u.getId();
    Map<String, Object> user = appUserService.findOneDetailById(userId);
    mv.addObject("model", user);
    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    List<AppDict> list = appDictService.findByType("PORTAL_CVENTER_CONFIG");
    mv.addObject("list", list);
    return mv;
  }

  @RequestMapping("myTaskEdit")
  public ModelAndView myTaskEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    IUser u = ContextHolder.getLoginUser();
    String username = u.getUsername();
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    List<Map<String, Object>> list = jdbcTemplate
        .queryForList("CALL `sp_getuser_task`('" + username + "')");
    mv.addObject("listSize", list.size());
    mv.addObject("list", list);
    return mv;
  }

  @RequestMapping("topKnowledgeEdit")
  public ModelAndView topKnowledgeEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    List<KngKnowledgeItem> klg = kngKnowledgeItemService.getNewTop10Item(5, "");
    mv.addObject("newTop10Entities", klg);
    return mv;
  }

  @RequestMapping("topAnnounceEdit")
  public ModelAndView topAnnounceEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    AnnouncementService announcementService = ContextHolder
        .getSpringBean("announcementService");
    List<AnnoAnnouncement> klg = announcementService.getNewTop10Item(5);
    mv.addObject("newTop10Entities", klg);
    return mv;
  }

  @RequestMapping("top10Edit")
  public ModelAndView top10Edit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    return mv;
  }

  @RequestMapping("userRequestEdit")
  public ModelAndView userRequestEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    return mv;
  }

  @RequestMapping("unCloseIcdStatusEdit")
  public ModelAndView unCloseIcdStatusEdit(HttpServletRequest req)
      throws Exception {
    ModelAndView mv = this.getModelAndView();
    return mv;
  }

  @RequestMapping("ciStatusEdit")
  public ModelAndView ciStatusEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    return mv;
  }

  @RequestMapping("sysLinkEdit")
  public ModelAndView sysLinkEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    return mv;
  }

  // 按照工程师本月创建知识库
  @RequestMapping("incidentGetEgCreateKnowledge")
  @ResponseBody
  public Option incidentGetEgCreateKnowledge() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,creator_name AS NAME FROM `kng_knowledge_item` where date_format(create_date,'%Y-%m')=date_format(now(),'%Y-%m') GROUP BY creator_name) t ";
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
    return getPieJsonDate(list);
  }

  // 工程师本月处理工单数
  @RequestMapping("incidentGetEgHandleIcd")
  @ResponseBody
  public Option incidentGetEgHandleIcd() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,solver_name AS NAME FROM `icd_incident` WHERE DATE_FORMAT(create_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') AND  solver_name IS NOT NULL GROUP BY solver_name) t  ORDER BY VALUE DESC limit 10";
    return getBarOption(sql);
  }

  @RequestMapping("incidentGetProjectUnCloseIcdCount")
  @ResponseBody
  public Option incidentGetProjectUnCloseIcdCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,IFNULL(b.name,'空') AS NAME FROM `icd_incident` a LEFT JOIN proj_project b ON a.`project_id`=b.id WHERE a.status<>'已关闭'  GROUP BY b.name) t ORDER BY VALUE DESC limit 10";
    return getBarOption(sql);
  }

  @RequestMapping("incidentGetStatusUnCloseIcdCount")
  @ResponseBody
  public Option incidentGetStatusUnCloseIcdCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,IFNULL(status,'空') AS NAME FROM `icd_incident`  WHERE (STATUS<>'已关闭' and status<>'新建')  GROUP BY status) t ORDER BY VALUE DESC";
    return getBarOption(sql);
  }

  @RequestMapping("incidentGetPriUnCloseIcdCount")
  @ResponseBody
  public Option incidentGetPriUnCloseIcdCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,IFNULL(priority_name,'空') AS NAME FROM `icd_incident`  WHERE STATUS<>'已关闭'  GROUP BY priority_name) t ORDER BY VALUE DESC";
    return getBarOption(sql);
  }

  @RequestMapping("incidentGetEgUnCloseIcdCount")
  @ResponseBody
  public Option incidentGetEgUnCloseIcdCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,IFNULL(supporter_name,'空') AS NAME FROM `icd_incident`  WHERE STATUS<>'已关闭' AND supporter_name IS NOT NULL AND supporter_name<>'' GROUP BY supporter_name) t ORDER BY VALUE DESC limit 10";
    return getBarOption(sql);
  }

  // 按照Sla排行
  @RequestMapping("incidentGetSlaCount")
  @ResponseBody
  public Option incidentGetSlaCount() {
    String sql = "SELECT * FROM (SELECT (1-SUM(CASE WHEN sla_status=1 THEN 1 ELSE 0 END )/COUNT(1))*100 VALUE,solver_name AS NAME FROM `icd_incident`  WHERE DATE_FORMAT(create_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')  AND solver_name IS NOT NULL GROUP BY solver_name) t ORDER BY VALUE DESC limit 10";
    return getBarOption(sql);
  }

  @RequestMapping("getUserNewRequestCount")
  @ResponseBody
  public long getUserNewRequestCount() {
    String sql = "SELECT COUNT(1) ct FROM icd_incident WHERE process_id IS NOT NULL AND (supporter_id IS NULL or supporter_id='') AND STATUS IN('待分派','一线分派','服务台分派')";
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    return jdbcTemplate.queryForObject(sql, Long.class);
  }

  // 按照满意度
  @RequestMapping("incidentGetSatisfactionCount")
  @ResponseBody
  public Option incidentGetSatisfactionCount() {
    String sql = "SELECT * FROM (SELECT AVG(satisfaction) AS VALUE,solver_name AS NAME FROM `icd_incident`  WHERE DATE_FORMAT(create_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')  AND satisfaction IS NOT NULL AND solver_name IS NOT NULL AND satisfaction<>0 GROUP BY solver_name) t ORDER BY VALUE DESC";
    return getBarOption(sql);
  }

  // ------------------资产相关-------------------//
  // 维保
  @RequestMapping("confGetCimtCount")
  @ResponseBody
  public Option confGetCimtCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,mainctmonth AS NAME FROM `v_conf_ci_forportal` WHERE  mainctmonth<>'未过期' GROUP BY mainctmonth) t ORDER BY NAME ASC";
    return getBarOption(sql);
  }

  // 状态
  @RequestMapping("confGetCiStatusCount")
  @ResponseBody
  public Option confGetCiStatusCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,status AS NAME FROM `v_conf_ci_forportal`  GROUP BY status) t ORDER BY NAME ASC";
    return getBarOption(sql);
  }

  // 年限
  @RequestMapping("confGetCiUseYearCount")
  @ResponseBody
  public Option confGetCiUseYearCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,inuseyear AS NAME FROM `v_conf_ci_forportal`  GROUP BY inuseyear) t ORDER BY VALUE DESC";
    return getBarOption(sql);
  }

  // 按客户
  @RequestMapping("confGetCiCustomerCount")
  @ResponseBody
  public Option confGonfGetCiCustomerCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,cus_name AS NAME FROM `v_conf_ci_forportal`  GROUP BY cus_name) t ORDER BY VALUE DESC limit 10";
    return getBarOption(sql);
  }

  // 按分类
  @RequestMapping("confGetCiCategoryCount")
  @ResponseBody
  public Option confGetCiCategoryCount() {
    String sql = "SELECT * FROM (SELECT COUNT(1) AS VALUE,category_name AS NAME FROM `v_conf_ci_forportal`  GROUP BY category_name) t ORDER BY VALUE DESC LIMIT 10";
    return getBarOption(sql);
  }

  public Option getPieJsonDate(List<Map<String, Object>> list) {
    GsonOption option = new GsonOption();

    Series<?> p = null;
    p = new Pie();
    p.data().addAll(list);

    for (Map<String, Object> m : list) {
      option.legend().data()
          .add(m.get("name") == null ? Counter.LABEL_NULL : m.get("name"));
      option.legend().orient(Orient.vertical);
      option.legend().setX(0);
      option.legend().setY(0);
    }
    option.series().add(p);
    return option;

  }

  public Option getBarOption(String sql) {
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
    GsonOption option = new GsonOption();
    Series<?> p1 = null;
    p1 = new Bar();
    CategoryAxis x = new CategoryAxis();
    for (Map<String, Object> m : list) {
      x.data().add(m.get("name") == null ? Counter.LABEL_NULL : m.get("name"));
      p1.data().add(m.get("value"));
    }
    option.xAxis().add(x);
    option.series().add(p1);
    return option;
  }

  @RequestMapping("dataForCiEdit")
  public ModelAndView dataForCiEdit(HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    CusCustomerService cusCustomerService = ContextHolder
        .getSpringBean("cusCustomerService");
    mv.addObject("customerCiCounts", cusCustomerService.getCustomerCiCount());
    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));
    String fromType = req.getParameter("fromType");
    if (StringUtils.isNotEmpty(fromType)) {
      String key = req.getParameter("key");
      String ename = req.getParameter("ename");
      mv.addObject("fromType", fromType);
      mv.addObject("key", key);
      mv.addObject("value", ename);
    }
    return mv;
  }

}
